package com.scau.clothes.service.impl;

import com.scau.clothes.service.MailService;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MailServiceImpl implements MailService {
    @Autowired
    JavaMailSender mailSender;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Value("${spring.mail.username}")
    private String from;
    @Override
    public void sendMail(String receiver, String title, String content) {
        HashMap<String, String> info = new HashMap<>();
        info.put("receiver",receiver);
        info.put("title",title);
        info.put("content",content);
        rabbitTemplate.convertAndSend("mailQ",info);
    }
    @RabbitListener(queuesToDeclare = @Queue("mailQ"))
    private void handleSendMail(Map<String,String> info){
        String receiver = info.get("receiver");
        String title = info.get("title");
        String content = info.get("content");
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(receiver);
        simpleMailMessage.setSubject(title);
        simpleMailMessage.setText(content);
        mailSender.send(simpleMailMessage);
    }
}
